<?php
class model_CommentMapper {
    private $table = 'comments';

    public function  __construct() {
        model_ConfigMapper::connect();
    }

    

    public function find($id) { //находим сообщение, записываем его содержание в свойства объекта
        $query = 'SELECT * from '. $this->table .' WHERE id = '. $id;
        $result = mysql_query($query);
        $row = mysql_fetch_array($result);

        if ($row) {
            $m = new model_CommentModel($row);
        } else { $m = new CommentsModel(null);
        }

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $m;
    }

    public function fetchAll($id) {
        $query = 'SELECT * from '. $this->table .' WHERE parentid = '.$id.' ORDER BY `id` ASC';
        $result = mysql_query($query);

        $entries = array();
        while ($row = mysql_fetch_array($result)) {
            $entry = new model_CommentModel($row);
           
            $entries[] = $entry;
        }

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();

        return $entries;
    }

    public function save($model) {
        $query = 'INSERT INTO '.$this->table.' (parentid, text, author, date) VALUES ("'. $model->getParentid() .'","'. $model->getText() .'","'. $model->getAuthor() .'","'. $model->getDate() .'")';
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
    }

    public function delete($id) {
        $query = 'DELETE FROM '. $this->table .' WHERE id='.$id;
        $result = mysql_query($query);

        $timer = model_ConfigMapper::instance();
        $timer->setSqlCounter();
    }
}